from scapy.all import rdpcap
import struct

#  192.168.2.2 0xc0a80202
def to_int(ip_str):
	i = 0
	ip_int = 0
	for ip_part in ip_str.split('.')[::-1]:
		ip_int = ip_int + int(ip_part) * 256**i
		i += 1
	return ip_int

packets = rdpcap("M:\\四牌楼服务器\\20\\2021_0610_1104_16.pcap")

with open('C:\\Users\\Password\\Desktop\\HK\\u2', 'wb')as f:
    for packet in packets:
        if "TCP" in packet and packet['TCP'].payload:
            src_ip = packet["IP"].src
            dst_ip = packet["IP"].dst
            src_port = packet["TCP"].sport
            dst_port = packet["TCP"].dport
            protocol = packet.proto

            # print(src_ip, dst_ip, src_port, dst_port)
            
            a = struct.pack('<I', to_int(src_ip))
            b = struct.pack('<I', to_int(dst_ip))
            c = struct.pack('<H', src_port)
            d = struct.pack('<H', dst_port)
            e = struct.pack('<B', protocol)

            #print(c, d, e)

            f.write(a + b + c + d + e)          # 4 + 4 + 2 + 2 + 1 = 13 bytes